package com.lewis.fragmenttest;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

//如果当前的类继承ActionBarActivity，则FragmentManager必须来自v4包这样addToBackStack(null)是有效的
public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new onClick());
    }

    private class onClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.button:
                    //创建待添加的碎片实例
                    AnotherRightFragment fragment = new AnotherRightFragment();
                    //获取FragmentManager
                    FragmentManager fragmentManager = getSupportFragmentManager();
                    //开启一个事务
                    FragmentTransaction transaction = fragmentManager.beginTransaction();
                    //向容器内添加碎片
                    transaction.replace(R.id.right_layout,fragment);
                    //将一个事务添加到返回栈中
                    transaction.addToBackStack(null);
                    //提交事务
                    transaction.commit();
                    break;
                default:
                    break;
            }
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
